<?php

/**
 *
 * PHP version 5
 *
 * @category Controller
 * @package  MIAOCMS
 * @version  1.0
 * @author   Arlon <MIAOCMS@google.com>
 * @link     http://www.MIAOCMS.net
 */

class WeixinController extends OauthAppController {
	
	var $components = array(
			'Session',
			'Cookie' => array('name' => 'MIAOCMS', 'time' => '+2 weeks'),
	);
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->Hook->loadhook('UCenterHook');
	}
	
	
	public function qrlogin(){
	   $this->autoLayout = false;
	   $this->set('qrAppID',wxdb63d9a5dad49e67);
	   
	   $_REQUEST['state'] = $_REQUEST['state'] ? $_REQUEST['state'] : 'qrlogin';
	   // 模板中调用微信js显示登录二维码
	   /**
	    * 申请的网站的应用的AppID与AppSecret。非公众号的
	    * 135平台
	    * AppID：wxdb63d9a5dad49e67
        * AppSecret：9298e67723605dc196e14910f693f22b重置
	    */
	}

	public function pbcallback(){
	    $_REQUEST['state'] = 'weixinPb';
	    $this->qrcallback();
    }
	
	public function qrcallback(){
	    /**
	     * 申请的网站的应用的AppID与AppSecret。非公众号的
	     * AppID：wxdb63d9a5dad49e67
	     * AppSecret：9298e67723605dc196e14910f693f22b重置
	     */
	    $this->pageTitle = __('Wechat Login');
	
	    $state =  $_REQUEST['state'];

        if($state == 'weixinPb'){
            $appid = Configure::read('Weixin.AppId');
            $secret = Configure::read('Weixin.AppSecret');
            $source = 'weixinPb'; // 微信中访问网站，公众号申请获取用户信息
        }
        else{  // 二维码扫描登录网站,网站平台申请二维码登录
            $appid = 'wxdb63d9a5dad49e67';
            $secret = '9298e67723605dc196e14910f693f22b';
            $source = 'weixinQr';
        }

	    $this->loadModel('User');
	    $this->loadModel('Oauthbind');
	    
	    $this->set('source',$source);
	    $loginfo = $this->Session->read('WechatLogin');
	    if(empty($loginfo) || empty($loginfo['userinfo']) || $loginfo['code'] != $_REQUEST['code']) 
	    {
	        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$_REQUEST['code'].'&grant_type=authorization_code';
	        App::uses('RequestFacade', 'Network');
	        $response =  RequestFacade::get($url);
	
	        $ret  = json_decode($response->body,true);
	        if($ret['access_token'] && $ret['openid']){

                CakeLog::debug("Weixin Login Callback:".var_export($_REQUEST,true).var_export($ret,true));

                $oauth_bind = $this->Oauthbind->find('first', array(
                    'conditions' => array(
                        'oauth_openid' => $ret['openid'],
                        'source' => $source,
                    ),
                ));
	            if( empty($oauth_bind) && $ret['unionid'] ) {
                    $oauth_bind = $this->Oauthbind->find('first', array(
                        'conditions' => array(
                            'unionid' => $ret['unionid'],
                        ),
                    ));
	            }

	            $uid = $oauth_bind['Oauthbind']['user_id'];
	            	
	            $userinfo_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$ret['access_token'].'&openid='.$ret['openid'].'&lang=zh_CN';
	            $response =  RequestFacade::get($userinfo_url);
	            $userinfo  = json_decode($response->body,true);
	            if(empty($userinfo) || $userinfo['errcode']){
	                echo $response;exit;
	            }
	            $this->Session->delete('WechatLogin');
	
	            $userinfo['oauth_bind'] = $oauth_bind;
	            $userinfo['oauth_openid'] = $ret['openid'];
	            $userinfo['unionid'] = $ret['unionid'];
	            $userinfo['access_token'] = $ret['access_token'];
	            $userinfo['expires_in'] = $ret['expires_in'];
	            $userinfo['refresh_token'] = $ret['refresh_token'];
	            
	            $this->Session->write('weixin_auth_user', $userinfo);
	            $this->Session->write('weixin_auth_ret', $ret);
	        }
	        else{
	            echo "get access_token error. $appid==={$_REQUEST['code']}";
	            print_r($_REQUEST);
	            echo $response;exit;
	        }
	    }
	    else{
	        //list($source,$userinfo) = $loginfo;
	        $ret = $this->Session->read('weixin_auth_ret');
	        $source = $loginfo['source'];
	        $userinfo = $loginfo['userinfo'];
	        $oauth_bind = $userinfo['oauth_bind'];
	        $uid = $oauth_bind['Oauthbind']['user_id'];
	    }

        $client_ip = $this->request->clientIp();
	    // $db_user 为库中的用户信息， $userinfo 为oauth取的微信用户的信息
	    if( !empty($oauth_bind) && $uid ){
	        $current_time = date('Y-m-d H:i:s');
	        
	        // 登录成功
	        $updateinfo = array(
	            'image' => $this->User->escape_string($userinfo['headimgurl']),
	            'nickname' => $this->User->escape_string($userinfo['nickname']),
	            'last_login' => $this->User->escape_string($current_time),
                'client_ip' => $this->User->escape_string($client_ip),
	        );
	        
	        $this->User->updateAll($updateinfo, array('id' => $uid));
	        
	        if($source == $oauth_bind['Oauthbind']['source'] && $oauth_bind['Oauthbind']['oauth_openid'] == $userinfo['oauth_openid'] ) {
	            // 更新oauth信息
	            $oauth_bind['Oauthbind']['created'] = time();
	            $oauth_bind['Oauthbind']['oauth_token'] = $ret['access_token'];
	            $oauth_bind['Oauthbind']['unionid'] = $ret['unionid'];
	            $oauth_bind['Oauthbind']['expires'] = $ret['expires_in'];
	            $oauth_bind['Oauthbind']['refresh_token'] = $ret['refresh_token'];
	            $this->Oauthbind->save($oauth_bind);
	        }
	        else{ // 网站扫码登录后，微信中打开网页中登录
	            $this->Oauthbind->create();
	            
	            $oauth_bind['Oauthbind'] = array();
	            $oauth_bind['Oauthbind']['user_id'] = $uid;
	            $oauth_bind['Oauthbind']['oauth_openid'] = $ret['openid'];
	            $oauth_bind['Oauthbind']['oauth_name'] = $userinfo['nickname'];
	            $oauth_bind['Oauthbind']['source'] = $source;
	            $oauth_bind['Oauthbind']['created'] = time();
	            $oauth_bind['Oauthbind']['oauth_token'] = $ret['access_token'];
	            $oauth_bind['Oauthbind']['unionid'] = $ret['unionid'];
	            $oauth_bind['Oauthbind']['expires'] = $ret['expires_in'];
	            $oauth_bind['Oauthbind']['refresh_token'] = $ret['refresh_token'];
	            $this->Oauthbind->save($oauth_bind);
	        }

	        $db_user = $this->User->getUserInfo($uid);
	
	        $this->Session->write('Auth.User', $db_user['User']);
	        $this->Cookie->write('Auth.User',array('id' => $db_user['User']['id'],'username' => $db_user['User']['username'],'email' => $db_user['User']['email'] ), true, 2592000);
	        $this->Session->delete('WechatLogin');
	        
    		$this->_success($uid,$state);    	    	
	        exit;
	    }
	    else{
	    	
	    	if( !empty($this->currentUser['id']) ) { // 对于已用网站账号登录的用户，再第三方扫码登录的，直接绑定
	    		$hasbind = $this->Oauthbind->find('first',array( 'conditions' => array('user_id' => $this->currentUser['id'],'source'=> $source )));
	    		if( empty($hasbind) ){ // 绑定已登录的135账号
	    			$this->__message('这个登录账号已经绑定过微信号了，一个绑定只能绑定一个微信号。');
	    			$oauth_bind = array(
	    					'user_id' => $this->currentUser['id'],
	    					'oauth_openid' => $ret['openid'],
	    					'oauth_name' => $userinfo['nickname'],
	    					'oauth_token' => $ret['access_token'],
	    					'source' => $source,
	    			);
	    			$this->Oauthbind->save($oauth_bind);
	    			
	    			$this->_success($this->currentUser['id'],$_REQUEST['state']);
	    			exit;
	    		}
	    	}
	    	
	    	/********使用自动注册用户的方式***************/
	    	$login_token = $this->Session->read('weixin_auth_ret');
	    	$third_user = $this->Session->read('weixin_auth_user');
	    	$this->autoRegister($login_token,$third_user);


            /****** 下面的是跳转到模板页面输入用户名与密码，选择自动创建账号还是绑定已有账号********/
	    	/*
	        $this->set('source',$source);
	        $this->set('userinfo',$userinfo);
            $this->Session->write('WechatLogin',array( 'source'=>$source, 'userinfo'=>$userinfo,'code'=>$_REQUEST['code'] ));

	        $this->layout = 'default';
	        $this->autoRender = true;*/
	    }
	}

    public function urilogin(){
        
    }
    
    private function getUserInfo($openid,$access_token) {
    	$userinfo_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
    	$response =  RequestFacade::get($userinfo_url);
    	$userinfo  = json_decode($response->body,true);
    	if(empty($userinfo)){
    		echo 'wechat userinfo error:';
    		echo $response;exit;
    	}
    	return $userinfo;
    }
        
    public function bind(){
    	
        if( empty($this->data['User']['email']) ) {
    		$this->__message(__('邮箱不能为空'));
    	}
    	
    	if(in_array($_REQUEST['source'],array('weixinQr','weixinPb'))) {
    	    $source = $_REQUEST['source'];
    	}
        elseif(in_array($_REQUEST['state'],array('weixinQr','weixinPb'))) {
            $source = $_REQUEST['state'];
        }
    	else{
    	    $source = 'weixinQr';
    	}
    	
    	$state =  $_REQUEST['state'];
    	
    	$this->autoRender =  false;
    	$this->loadModel('User');$this->loadModel('Oauthbind');
    	
    	if(Validation::email($this->data['User']['email'])) {
    	    $userinfo = $this->User->getUserByEmail($this->data['User']['email']);
    	}
    	else{
    	    $userinfo = $this->User->getUserByMobile($this->data['User']['email']);
    	}
    	
    	if( !empty($userinfo) && Security::hash($this->data['User']['password'] , null, true) == $userinfo['User']['password'] ) {
    	
    	    $login_token = $this->Session->read('weixin_auth_ret');
    	    $third_user = $this->Session->read('weixin_auth_user');
    	    
    	    $user_id = $userinfo['User']['id'];
    	    $this->loadModel('Oauthbind');
    	    $oauth_bind = $this->Oauthbind->find('first', array(
    	        'conditions' => array(
    	            'oauth_openid' => $login_token['openid'],
    	            'user_id' => $user_id,
    	            'source' => $source,
    	        ),
    	    ));
    	
    	    if (empty($oauth_bind)) {  // 没有绑定过的账号。
    	        $oauth_bind = array(
    	            'user_id' => $user_id,
    	            'oauth_openid' => $login_token['openid'],
    	            'oauth_name' => $third_user['nickname'],
    	            'unionid' => $login_token['unionid'],
    	            'expires' => $login_token['expires_in'],
    	            'refresh_token' => $login_token['refresh_token'],
    	            'oauth_token' => $login_token['access_token'],
    	            'source' => $source,
    	        );
    	        $this->Oauthbind->save($oauth_bind);
    	    } else {
    	        $oauth_bind['Oauthbind']['unionid'] = $login_token['unionid'];
    	        $oauth_bind['Oauthbind']['oauth_name'] = $third_user['nickname'];
    	        $oauth_bind['Oauthbind']['updated'] = date('Y-m-d H:i:s');
    	        $oauth_bind['Oauthbind']['oauth_token'] = $login_token['access_token'];
    	        $this->Oauthbind->save($oauth_bind);
    	    }
    	    $this->Session->write('Auth.User', $userinfo['User']);
    	    $this->Cookie->write('Auth.User', array(
    	        'id' => $userinfo['User']['id'],
    	        'username' => $userinfo['User']['username'],
    	        'email' => $userinfo['User']['email'],
    	        'roles' => count($userinfo['User']['role_id']),
    	    ), true, 2592000);
    	
    	    $this->_success($user_id,$state);    	    	
    	}
    	else{
    	    echo json_encode(array('ret' => -1,'error'=>'用户邮箱或者密码错误'));
    	}
    	exit;
    }
    
    private function autoRegister($login_token,$third_user){
        if(empty($third_user['nickname'])) {
            $third_user['nickname'] = substr(md5($login_token['openid']),0,16);
        }
        
        if(empty( $this->data['User']['password'] )){
            $this->data['User']['password'] = random_str(12);
        }
        
        if ($third_user['gender'] == '男' || $third_user['gender']==1) {
            $gender = 1; //男
        } else {
            $gender = 0; //女
        }
        $current_time = date('Y-m-d H:i:s');
        
        if( in_array($_REQUEST['source'],array('weixinQr','weixinPb')) ) {
            $source = $_REQUEST['source'];
        }
        elseif( in_array($_REQUEST['state'],array('weixinQr','weixinPb')) ) {
            $source = $_REQUEST['state'];
        }
        else{
            $source = 'weixinQr';
        }

        $client_ip = $this->request->clientIp();

        $userinfo = array(
            'password' => Security::hash($this->data['User']['password'], null, true),
            'username' => $third_user['nickname'],
            'image' => $third_user['headimgurl'],
            'sex' => $gender,
            'role_id' => 2,
            'last_login' => $current_time,
            'client_ip' => $client_ip,
            'created' => $current_time,
            'city' => $third_user['city'],
            'province' => $third_user['province'],
            'activation_key' => md5(uniqid()),
            'status' => 1,
        );
        $this->loadModel('User');
        $this->loadModel('Oauthbind');
        if( $this->User->save($userinfo) ) {
        
            $userinfo['id'] = $user_id = $this->User->getLastInsertID();
            $this->Session->write('Auth.User', $userinfo);
            $this->Cookie->write('Auth.User', $userinfo, true, 2592000);
        
            $this->Session->delete('WechatLogin');
        
            $oauth_bind = array(
                'user_id' => $user_id,
                'oauth_openid' => $login_token['openid'],
                'oauth_name' => $third_user['nickname'],
                'oauth_token' => $login_token['access_token'],
                'unionid' => $login_token['unionid'],
                'expires' => $login_token['expires_in'],
                'refresh_token' => $login_token['refresh_token'],
                'source' => $source,
            );
            $this->Oauthbind->save($oauth_bind);
            
            $redirect = $this->Session->read('Auth.redirect');
            $redirect = $redirect ? $redirect : '/users/index';
            if($redirect == '/users/login') {
                $redirect = '/users/index';
            }
            $this->Session->delete('Auth.redirect');
            $this->redirect($redirect);
            
        }
        else{
            $this->__message(__('创建用户错误，请稍候重试或联系客服。') );
        }
    }
    
    public function register(){
        $this->autoRender = false;
        $login_token = $this->Session->read('weixin_auth_ret');
        $third_user = $this->Session->read('weixin_auth_user');
        
        if ($third_user['gender'] == '男' || $third_user['gender']==1) {
            $gender = 1; //男
        } else {
            $gender = 0; //女
        }
        $current_time = date('Y-m-d H:i:s');
        
        if(in_array($_REQUEST['source'],array('weixinQr','weixinPb'))) {
            $source = $_REQUEST['source'];
        }
        elseif(in_array($_REQUEST['state'],array('weixinQr','weixinPb'))) {
            $source = $_REQUEST['state'];
        }
        else{
            $source = 'weixinQr';
        }
        $state =  $_REQUEST['state'];
    
        $referer =  $this->request->referer();
        
//         if( empty($this->data['User']['email']) ) {
//         	$this->data['User']['email'] = substr(md5($login_token['openid']),0,16).'@135editor.com';
//         }
        if(empty($third_user['nickname'])) {
        	$third_user['nickname'] = substr(md5($login_token['openid']),0,16);
        }
        
        if( $this->data['User']['password'] != $this->data['User']['password_confirm']  ) {
            $this->__message(__('密码与确认密码不一致'), $referer);
        }
        
        if(empty( $this->data['User']['password'] )){
        	$this->data['User']['password'] = random_str(12);
        }
        
        $userinfo = array(
//             'email' => $this->data['User']['email'],
            'password' => Security::hash($this->data['User']['password'], null, true),
            'username' => $third_user['nickname'],
            'image' => $third_user['headimgurl'],
            'sex' => $gender,
            'role_id' => 2,
            'last_login' => $current_time,
            'created' => $current_time,
            'city' => $third_user['city'],
            'province' => $third_user['province'],
            'activation_key' => md5(uniqid()),
            'status' => 1,
        );
        $this->loadModel('User');
        $this->loadModel('Oauthbind');
        if( $this->User->save($userinfo) ) {
    
            $userinfo['id'] = $user_id = $this->User->getLastInsertID();
            $this->Session->write('Auth.User', $userinfo);
            $this->Cookie->write('Auth.User', $userinfo, true, 2592000);
    
            $this->Session->delete('WechatLogin');
            
            $oauth_bind = array(
                'user_id' => $user_id,
                'oauth_openid' => $login_token['openid'],
                'oauth_name' => $third_user['nickname'],
                'oauth_token' => $login_token['access_token'],
                'unionid' => $login_token['unionid'],
                'expires' => $login_token['expires_in'],
                'refresh_token' => $login_token['refresh_token'],
                'source' => $source,
            );
            $this->Oauthbind->save($oauth_bind);
            $this->_success($user_id,$state);
        }
        else{
            $errors = $this->User->invalidFields();
            print_r($errors);
        }
        exit;    
    }
    
    /**
     * 微信登录，申请开通的域名为www.135plat.com. 需要同步登录 135editor.com
     * @param unknown $uid
     * @param unknown $state
     */
    private function _success($uid,$state){
    	
//     	echo "===$uid,$state=====";
    	$appkey = '57326a20-e9cc-461a-8b90-199c9fde689a';
    	$secretKey = 'WYFDXgFMZPFiilBdCWGfqyjSLf1SAsSMG9Pxxz2COLcN';
    	
    	$ts = time();
    	$u = Security::rijndael($uid, $secretKey, 'encrypt');
    	
//     	echo Security::rijndael($u, $secretKey, 'decrypt');
    	$u = base64_encode($u);
    	$sign = md5($appkey.$secretKey.$u.$ts);
    	
    	if($state == '135plat') { //从135域名登录。则不用跳转到135编辑器同步登录
    		$url = 'http://www.135editor.com/users/login?a=appsync&ts='.$ts.'&appkey='.$appkey.'&u='.urlencode($u).'&state='.$state.'&sign='.$sign;
    		//$this->redirect($url);
    		$this->Session->setFlash( __('Login Success').'<script type="text/javascript" src="'.$url.'"></script>');
    		$content = '已成功登录,窗口将自动关闭。<script>window.opener.location.reload(true);window.close();</script>';
    		$this->response->body($content);
    		$this->response->send();
    		exit;
    	}
    	elseif($state == 'weixinPb') {
    	    //$url = 'http://www.135editor.com/users/index';
    	    //$this->Session->read('');
    	    $redirect = $this->Session->read('Auth.redirect');
    	    $redirect = $redirect ? $redirect : '/users/index';
    	    if($redirect == '/users/login') {
    	        $redirect = '/users/index';
    	    }
    	    $this->Session->delete('Auth.redirect');
    	    $this->redirect($redirect);
    	}
    	else{
    		$url = 'http://www.135editor.com/users/login?a=appsync&ts='.$ts.'&appkey='.$appkey.'&u='.urlencode($u).'&state='.$state.'&sign='.$sign;
    		$this->redirect($url);
    	}
    }
}

?>